package com.chen.palmar.common.utils;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: json数据的解析工具类（gson）
 * 创建作者: Chen
 */
public class GsonUtils {
	/**
	 * 对单个javabean进行解析
	 * @param <T>
	 * @param jsonString	要解析的json字符串
	 * @param cls	实体bean的字节码对象
	 * @return		
	 */
	public static <T> T getObject(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 对list类型进行解析
	 * @param <T>
	 * @param jsonString	要解析的json字符串
	 * @param cls	实体bean的字节码对象
	 * @return
	 */
	public static <T> List<T> getObjects(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
			}.getType());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 对listString类型进行解析
	 * @param jsonString
	 * @return
	 */
	public static List<String> getList(String jsonString) {
		List<String> list = new ArrayList<String>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;

	}
	/**
	 * 对listmap类型进行解析
	 * @param jsonString	要解析的json字符串
	 * @return
	 */
	public static List<Map<String, Object>> getListKeyMap(String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}
	/**
	 * 对MapString类型数据进行解析
	 * @param jsonString	要解析的json字符串
	 * @return
	 */
	public static Map<String, Object> getKeyMap(String jsonString) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Gson gson = new Gson();
			map = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}

}
